
#include<Dialect/Agile/Mesh.h>

_BeginNamespace(Radix)

Mesh::Vertex::Vertex()
	:position(), normal(), color(), uv()
{}

Mesh::Vertex::Vertex(const Vector3& position, const Vector3& normal, const Color& color, const Vector2& uv)
	:position(position), normal(normal), color(color), uv(uv)
{}

Mesh::Triangle::Triangle()
	:v1(0), v2(0), v3(0)
{}

Mesh::Triangle::Triangle(uint v1, uint v2, uint v3)
	:v1(v1), v2(v2), v3(v3)
{}

Mesh::Mesh()
	:mVertices(),
	mTriangles()
{}

Mesh::~Mesh()
{}

const Mesh::Vertex* Mesh::vdata() const
{
	return mVertices.data();
}

uint Mesh::vcount() const
{
	return mVertices.size();
}

const Mesh::Triangle* Mesh::tdata() const
{
	return mTriangles.data();
}

uint Mesh::tcount() const
{
	return mTriangles.size();
}

Mesh::Vertex& Mesh::vertex(uint i)
{
	return mVertices.at(i);
}

Mesh::Triangle& Mesh::triangle(uint i)
{
	return mTriangles.at(i);
}

void Mesh::appendVertex(const Vertex& vertex)
{
	mVertices.push_back(vertex);
}

void Mesh::appendTriangle(const Triangle& triangle)
{
	mTriangles.push_back(triangle);
}

void Mesh::setVertices(Vertex* vertices, uint count)
{
	mVertices.clear();
	for(uint i=0; i<count; i++)
	{
		mVertices.push_back(*(vertices++));
	}
}

void Mesh::setTriangles(Triangle* triangles, uint count)
{
	mTriangles.clear();
	for(uint i=0; i<count; i++)
	{
		mTriangles.push_back(*(triangles++));
	}
}

void Mesh::loadFromFile(const String& fileName)
{
	File file(fileName, _T("rb+"));
	if(! file.open())
		return;

	uint vcount = 0;
	uint tcount = 0;
	file.read(&vcount, sizeof(vcount));
	file.read(&tcount, sizeof(tcount));

	Vertex* vdata = new Vertex[vcount];
	Triangle* tdata = new Triangle[tcount];
	file.read(vdata, sizeof(Vertex)*vcount);
	file.read(tdata, sizeof(Triangle)*tcount);

	file.close();

	this->setVertices(vdata, vcount);
	this->setTriangles(tdata, tcount);
}

void Mesh::saveToFile(const String& fileName)
{
	uint vcount = mVertices.size();
	uint tcount = mTriangles.size();
	Vertex* vdata = mVertices.data();
	Triangle* tdata = mTriangles.data();

	File file(fileName, _T("wb+"));
	if(! file.open())
		return;
	file.write(&vcount, sizeof(vcount));
	file.write(&tcount, sizeof(tcount));
	file.write(vdata, sizeof(Vertex)*vcount);
	file.write(tdata, sizeof(Triangle)*tcount);
	file.close();
}

_EndNamespace(Radix)
